package com.hwxm.ltim.netty;

import com.alibaba.fastjson2.JSON;
import com.hwxm.ltim.entity.message.MessageRequest;
import com.hwxm.ltim.service.MessageService;
import com.hwxm.ltim.util.ChannelManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * WebSocket 消息处理器
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class WebSocketHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    @Autowired
    private MessageService messageService;

    /**
     * 连接建立时
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端连接建立：{}", ctx.channel().id().asLongText());
    }

    /**
     * 连接断开时
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String channelId = ctx.channel().id().asLongText();
        log.info("客户端连接断开：{}", channelId);
        // 从通道管理器中移除
        ChannelManager.removeChannel(channelId);
    }

    /**
     * 接收到消息时
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
        if (frame instanceof TextWebSocketFrame) {
            String content = ((TextWebSocketFrame) frame).text();
            log.debug("收到消息：{}", content);

            try {
                // 解析消息
                MessageRequest request = JSON.parseObject(content, MessageRequest.class);
                // 处理消息
                messageService.handleMessage(ctx, request);
            } catch (Exception e) {
                log.error("消息处理失败", e);
            }
        }
    }

    /**
     * 异常处理
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("连接异常：{}", ctx.channel().id().asLongText(), cause);
        ctx.close();
    }

    /**
     * 心跳检测
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                log.info("客户端心跳超时，断开连接：{}", ctx.channel().id().asLongText());
                ctx.close();
            }
        }
        super.userEventTriggered(ctx, evt);
    }
}

